﻿@{
    ViewBag.Title = "Danh sách chức danh";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script type="text/javascript">

    var required = '<span style="color:red;font-weight:bold" data-qtip="Bắt buộc nhập">*</span>';

    Ext.Loader.setPath('Ext.ux', 'extjs/ux');

    Ext.require([
        'Ext.data.*',
        'Ext.grid.*',
        'Ext.tree.*',
        'Ext.ux.DataTip'
    ]);
    
    Ext.define('VTV.TaDMS.Extjs.Model.JobTitle', {
        extend: 'Ext.data.Model',
        fields: [{
            name: 'JobTitleId', mapping: 'JobTitleId', type: 'int'
        }, {
            name: 'ParentJobTitleId', mapping: 'ParentJobTitleId', type: 'int'
        }, {
            name: 'JobTitleName', mapping: 'JobTitleName', type: 'string'
        }, {
            name: 'Desicriptions', mapping: 'Desicriptions', type: 'string'
        }]
    });

    Ext.onReady(function () {
        Ext.QuickTips.init();

        var store = Ext.create('Ext.data.TreeStore', {
            model: 'VTV.TaDMS.Extjs.Model.JobTitle',
            proxy: {
                type: 'ajax',
                api: {
                    create: '/api/ApiJobTitle/Create',
                    read: '/api/ApiJobTitle/GetAll',
                    update: '/api/ApiJobTitle/Update',
                    destroy: '/api/ApiJobTitle/Delete'
                },
                reader: {
                    root: 'JobTitle1',
                    type: 'json',
                    successProperty: 'success',
                    messageProperty: 'message'
                },
                writer: {
                    type: 'json'
                },
                listeners: {
                    exception: function (proxy, response, operation) {
                        Ext.MessageBox.show({
                            title: 'Lỗi',
                            msg: operation.getError(),
                            icon: Ext.MessageBox.ERROR,
                            buttons: Ext.Msg.OK
                        });
                    }
                }
            },
            listeners: {
                write: function (store, operation) {
                    var record = operation.getRecords()[0],
                        name = Ext.String.capitalize(operation.action),
                        verb;


                    if (name == 'Destroy') {
                        record = operation.records[0];
                        verb = 'Destroyed';
                    } else {
                        verb = name + 'd';
                    }
                },
                append: function (thisNode, newChildNode, index, eOpts) {
                    if (!newChildNode.isRoot()) {
                        newChildNode.set('leaf', false);
                        newChildNode.set('expanded', true);
                        newChildNode.set('icon', '../Content/icon/bad.png');
                    }
                }
            }
        });

        var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
            listeners: {
                cancelEdit: function (editor, context) {
                    // Canceling editing of a locally added, unsaved record: remove it
                    if (context.record.phantom) {
                        store.remove(context.record);
                    }
                },
                edit: function (editor, e) {
                    if (e.record.isModified('JobTitleName') || e.record.isModified('Desicriptions')) {
                        var entity = {
                            JobTitleId: e.record.get('JobTitleId'),
                            JobTitleName: e.record.get('JobTitleName'),
                            Desicriptions: e.record.get('Desicriptions')
                        };
                        Ext.Ajax.request({
                            url: '/api/ApiJobTitle/Update',
                            method: 'POST',
                            jsonData: entity,
                            params: {
                                fields: 'JobTitleName$Desicriptions'
                            },
                            success: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                if (responseData.success == true) {
                                    e.record.commit();
                                } else {
                                    alert("Lỗi. " + responseData.message);
                                }
                            },
                            failure: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                alert("Lỗi. " + responseData.message);
                            }
                        });
                    }
                }
            }
        });

        var oldParentId = -1;
        var tree = Ext.create('Ext.tree.Panel', {
            title: 'Danh sách chức danh',
            layout: 'fit',
            minHeight: 200,
            rootVisible: false,
            store: store,
            useArrows: true,
            singleExpand: false,
            plugins: [rowEditing],
            viewConfig: {
                stripeRows: true,
                enableTextSelection: true,
                plugins: {
                    ptype: 'treeviewdragdrop',
                    containerScroll: true
                },
                listeners: {
                    beforedrop: function (node, data, overModel, dropPosition, dropHandlers, eOpts) {
                        oldParentId = data.records[0].parentNode.data.JobTitleId;
                    },
                    drop: function (node, data, overModel, dropPosition, eOpts) {
                        if (oldParentId != -1 && oldParentId != data.records[0].parentNode.data.JobTitleId) {

                            var entity = {
                                JobTitleId: data.records[0].data.JobTitleId,
                                ParentJobTitleId: data.records[0].parentNode.data.JobTitleId == 0 ? null : data.records[0].parentNode.data.JobTitleId,
                                JobTitleName: data.records[0].data.JobTitleName,
                                Desicriptions: data.records[0].data.Desicriptions
                            };

                            Ext.Ajax.request({
                                url: '/api/ApiJobTitle/Update',
                                method: 'POST',
                                jsonData: entity,
                                params: {
                                    fields: 'ParentJobTitleId'
                                },
                                success: function (transport, option) {
                                    var responseData = Ext.decode(transport.responseText);
                                    if (responseData.success == true) {
                                        alert("Thành công. " + responseData.message);
                                        //tree.getLoader().dataUrl = '/api/ApiJobTitle/GetAll';
                                        //tree.getLoader().load(tree.root);
                                        
                                    } else {
                                        alert("Lỗi. " + responseData.message);
                                    }
                                },
                                failure: function (transport, option) {
                                    var responseData = Ext.decode(transport.responseText);
                                    alert("Lỗi. " + responseData.message);
                                }
                            });
                        }
                    }
                }
            },

            columns: [{
                xtype: 'treecolumn',
                text: 'Tên chức danh',
                width: 300,
                dataIndex: 'JobTitleName',
                field: { xtype: 'textfield' }
            }, {
                text: 'Mô tả',
                flex: 1,
                dataIndex: 'Desicriptions',
                field: { xtype: 'textfield' }
            }, {
                menuDisabled: true,
                sortable: false,
                xtype: 'actioncolumn',
                text: 'Thao tác',
                align: 'center',
                width: 80,
                items: [{
                    icon: '../Content/icon/delete.gif',
                    tooltip: 'Xóa',
                    handler: function (grid, rowIndex, colIndex, item, e, record) {
                        //Ext.MessageBox.confirm('Xác nhận', 'Xác nhận xóa dữ liệu ?', function(btn) {
                        //    var a = btn;
                        //});
                        Ext.Msg.show({
                            title: 'Xác nhận',
                            msg: 'Xác nhận xóa dữ liệu ?',
                            width: 300,
                            buttons: Ext.MessageBox.OKCANCEL,
                            buttonText: {
                                ok: 'Xóa',
                                cancel: 'Hủy'
                            },
                            icon: Ext.MessageBox.QUESTION,
                            fn: function(buttonId, text, opt) {
                                if (buttonId == 'ok') {
                                    var rec = grid.getStore().getAt(rowIndex);
                                    if (rec) {
                                        var entity = {
                                            JobTitleId: rec.get('JobTitleId')
                                        };

                                        Ext.Ajax.request({
                                            url: '/api/ApiJobTitle/Delete',
                                            method: 'POST',
                                            jsonData: entity,
                                            success: function (transport, option) {
                                                var responseData = Ext.decode(transport.responseText);
                                                if (responseData.success == true) {

                                                    var gStore = tree.getStore();
                                                    var root = gStore.getRootNode();
                                                    var del = root.findChild('JobTitleId', rec.get('JobTitleId'), true);
                                                    del.remove();

                                                } else {
                                                    Ext.MessageBox.show({
                                                        title: 'Lỗi',
                                                        msg: responseData.message,
                                                        icon: Ext.MessageBox.ERROR,
                                                        buttons: Ext.Msg.OK
                                                    });
                                                }
                                            },
                                            failure: function (transport, option) {
                                                var responseData = Ext.decode(transport.responseText);
                                                Ext.MessageBox.show({
                                                    title: 'Lỗi',
                                                    msg: responseData.message,
                                                    icon: Ext.MessageBox.ERROR,
                                                    buttons: Ext.Msg.OK
                                                });
                                            }
                                        });
                                    }
                                }
                                else if (buttonId == 'cancel') {
                                    
                                }
                            }
                        });
                    }
                }]
            }],
            dockedItems: [{
                xtype: 'toolbar',
                items: [{
                    text: 'Thêm chức danh',
                    iconCls: 'icon-add',
                    handler: function () {
                        Ext.create('DepartmentWindow', {
                            id: 'newDepartmentWindow'
                        }).show();
                    }
                }]
            }]
        });

        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            items: [tree]
        });
        

        var comboStore = Ext.create('Ext.data.Store', {
            model: 'VTV.TaDMS.Extjs.Model.JobTitle',
            pageSize: 10,
            proxy: {
                type: 'ajax',
                api: {
                    read: '/api/ApiJobTitle/GetComboData'
                },
                reader: {
                    root: 'data',
                    type: 'json',
                    successProperty: 'success',
                    totalProperty: 'total'
                },
                listeners: {
                    exception: function (proxy, response, operation) {
                        Ext.MessageBox.show({
                            title: 'Lỗi',
                            msg: operation.getError(),
                            icon: Ext.MessageBox.ERROR,
                            buttons: Ext.Msg.OK
                        });
                    }
                }
            }
        });

        Ext.define('DepartmentWindow', {
            extend: 'Ext.window.Window',
            title: 'Chức danh',
            modal: true,
            header: {
                titleAlign: 'center'
            },
            closeable: true,
            resizable: {
                handles: 'e w'
            },
            width: 400,
            height: 300,
            layout: 'fit',
            items: {
                xtype: 'form',
                layout: 'form',
                bodyPadding: '10 10 5 10',
                fieldDefaults: {
                    msgTarget: 'side',
                    labelWidth: 100
                },
                plugins: {
                    ptype: 'datatip'
                },
                defaultType: 'textfield',
                items: [{
                    fieldLabel: 'Tên chức danh',
                    afterLabelTextTpl: required,
                    id: 'jobTitleName',
                    allowBlank: false,
                    tooltip: 'Nhập tên chức danh'
                }, {
                    xtype: 'combo',
                    id: 'comboboxD',
                    fieldLabel: 'Trực thuộc',
                    store: comboStore,
                    displayField: 'JobTitleName',
                    valueField: 'JobTitleId',
                    typeAhead: true,
                    typeAheadDelay: 300,
                    tooltip: 'Chọn chức danh',
                    selectOnFocus: true,
                    triggerAction: 'all',
                    listConfig: {
                        loadingText: 'Tìm kiếm',
                        emptyText: 'Không có kết quả phù hợp',
                        getInnerTpl: function () {
                            return '<div style="padding: 5px 5px 5px 10px; border-bottom: dotted 1px beige;">' +
                                '{JobTitleName}' +
                                '</div>';
                        }
                    },
                    pageSize: 10,
                    minChars: 2
                }, {
                    xtype: 'textareafield',
                    id: 'Desicriptions',
                    fieldLabel: 'Mo tả',
                    height: 150,
                    labelAlign: 'top',
                    grow: false,
                    anchor: '100%',
                    tooltip: 'Nhập mô tả'
                }]
            },
            buttons: [{
                text: 'Lưu',
                id: 'btnSave',
                handler: function () {
                    var entity = {
                        JobTitleName: Ext.getCmp('jobTitleName').getValue(),
                        ParentJobTitleId: (Ext.getCmp('comboboxD').valueModels[0]) ? Ext.getCmp('comboboxD').valueModels[0].get('JobTitleId') : null,
                        Desicriptions: Ext.getCmp('Desicriptions').getValue()
                    };
                    
                    Ext.Ajax.request({
                        url: '/api/ApiJobTitle/Create',
                        method: 'POST',
                        jsonData: entity,
                        success: function (transport, option) {
                            var responseData = Ext.decode(transport.responseText);
                            if (responseData.success == true) {
                                //alert("Success. " + responseData.message);

                                var treeStore = tree.getStore();
                                var rootNode = (treeStore) ? treeStore.getRootNode() : null;
                                if (entity.ParentJobTitleId == null) {
                                    var newNode1 = rootNode.createNode({
                                        leaf: false,
                                        expandable: true,
                                        expanded: true,
                                        icon: "../Content/icon/bad.png",
                                        JobTitleId: responseData.data.JobTitleId,
                                        ParentJobTitleId: responseData.data.ParentJobTitleId,
                                        JobTitleName: responseData.data.JobTitleName,
                                        Desicriptions: responseData.data.Desicriptions
                                    });
                                    
                                    rootNode.insertChild(0, newNode1);
                                } else {
                                    var currentNode = (rootNode) ? rootNode.findChild('JobTitleId', entity.ParentJobTitleId, true) : null;
                                    if (currentNode) {
                                        var newNode2 = currentNode.createNode({
                                            leaf: false,
                                            expandable: true,
                                            expanded: true,
                                            icon: "../Content/icon/bad.png",
                                            JobTitleId: responseData.data.JobTitleId,
                                            ParentJobTitleId: responseData.data.ParentJobTitleId,
                                            JobTitleName: responseData.data.JobTitleName,
                                            Desicriptions: responseData.data.Desicriptions
                                        });

                                        currentNode.insertChild(0, newNode2);
                                    }
                                }
                            } else {
                                alert("Error. " + responseData.message);
                            }
                        },
                        failure: function (transport, option) {
                            var responseData = Ext.decode(transport.responseText);
                            alert("Error: " + responseData.message);
                        }
                    });
                }
            }, {
                text: 'Hủy',
                handler: function() {
                    Ext.getCmp('newDepartmentWindow').close();
                }
            }]
        });
        
    /*End of onReady*/
    });

</script>
